<template>
  <div class="file-upload">
    <el-upload
      class="upload-area"
      drag
      multiple
      :action="uploadUrl"
      :headers="headers"
      :data="uploadData"
      :accept="acceptTypes"
      :before-upload="handleBeforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
    >
      <el-icon class="upload-icon"><Upload /></el-icon>
      <div class="upload-text">
        <span>将文件拖到此处，或<em>点击上传</em></span>
        <p>支持 PDF、Word、TXT、MD 格式文件</p>
      </div>
    </el-upload>
  </div>
</template>

<script setup>
import { Upload } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { computed } from 'vue'

const props = defineProps({
  knowledgeId: {
    type: [String, Number],
    required: true
  }
})

const emit = defineEmits(['upload-success'])

const acceptTypes = '.pdf,.doc,.docx,.txt,.md'

const uploadUrl = '/api/knowledge/upload' // 替换为实际的上传地址

const headers = computed(() => ({
  // 根据需要添加请求头
  'Authorization': `Bearer ${localStorage.getItem('token')}`
}))

const uploadData = computed(() => ({
  knowledgeId: props.knowledgeId
}))

const handleBeforeUpload = (file) => {
  const isValidType = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'text/plain',
    'text/markdown'
  ].includes(file.type)

  if (!isValidType) {
    ElMessage.error('不支持的文件类型！')
    return false
  }

  const isLt50M = file.size / 1024 / 1024 < 50

  if (!isLt50M) {
    ElMessage.error('文件大小不能超过 50MB！')
    return false
  }

  return true
}

const handleSuccess = (response) => {
  ElMessage.success('上传成功')
  emit('upload-success')
}

const handleError = () => {
  ElMessage.error('上传失败')
}
</script>

<style scoped>
.file-upload {
  margin: 20px 0;
}

.upload-area {
  width: 100%;
  background: var(--el-bg-color-page);
  border-radius: 6px;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.upload-icon {
  font-size: 48px;
  color: var(--el-text-color-secondary);
  margin-bottom: 10px;
}

.upload-text {
  text-align: center;
}

.upload-text em {
  color: var(--el-color-primary);
  font-style: normal;
}

.upload-text p {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  margin-top: 6px;
}
</style>
